package photogcalc.util;

import javax.microedition.rms.*;
import java.util.Hashtable;
import java.util.Enumeration;

import net.sf.microlog.core.Logger;
import net.sf.microlog.core.LoggerFactory;

/** Class to manage programs settings in a record store.
 *
 * @author Antti Okkonen
 * @version 2009-03-10 (modified 2010-02-22)
 */
public class Settings {

    private RecordStore rs = null;
    /** the name of the record store */
    private String name;
    /** readed records goes here */
    private Hashtable records = null;

    private Logger logger = LoggerFactory.getLogger("Settings");

    /** Default constructor.
        @param name The name of the application's record store.
     */
    public Settings(String name) {
        this.name = name;
        records = new Hashtable();
    }

    /** Opens the record store. */
    public void open() {
        logger.debug("open()");

        if (rs == null) {
            try {
                rs = RecordStore.openRecordStore(name, true);
                logger.debug("The record store '"+name+"' opened.");
            }
            catch (RecordStoreException e) {
                logger.warn(e.toString());
            }
        }
    }

    /** Closes the record store. */
    public void close() {
        logger.debug("Closing the record store '"+name+"'.");
        if (rs != null) {
            try {
                rs.closeRecordStore();
                rs = null;
                logger.debug("The record store closed.");
            }
            catch (RecordStoreException e) {
                logger.warn(e.toString());
            }
        }
    }

    /** Deletes the record store from the phones memory. */
    public void delete() {
        logger.debug("Deleting the record store '"+name+"'.");

        if (rs != null) {
            close();
        }

        try {
            RecordStore.deleteRecordStore(name);
            logger.debug("The record store deleted.");
        }
        catch (RecordStoreException e) {
            logger.warn(e.toString());
        }
    }

    /** Reads the records and puts those in the hastable. */
    public void readRecords() {
        logger.debug("Read records from the record store.");

        try {
            for (RecordEnumeration re = rs.enumerateRecords(null, null, false); re.hasNextElement();) {
                try {
                    String tmp = new String(re.nextRecord());
                    records.put(tmp.substring(0, tmp.indexOf("=")),
                            tmp.substring(tmp.indexOf("=") + 1));

                    logger.debug(tmp.substring(0, tmp.indexOf("=")) + ": " +
                            tmp.substring(tmp.indexOf("=") + 1));
                }
                catch (InvalidRecordIDException e) {
                    logger.warn(e.toString());
                }
                catch (RecordStoreException e) {
                    logger.warn(e.toString());
                }
            }
        }
        catch (RecordStoreNotOpenException e) {
            logger.warn(e.toString());
        }
    }

    /** Writes the records in the hashtable to the record store. */
    public void saveRecords() {
        logger.debug("Saving records to the record store.");

        if (records != null) {
            // delete old ones
            logger.debug("Deleting old records from the store.");
            int index;
            try {
                for (RecordEnumeration re = rs.enumerateRecords(null, null, false); re.hasNextElement();) {
                    try {
                        index = re.nextRecordId();
                        logger.debug("delete " + index);
                        rs.deleteRecord(index);
                    }
                    catch (InvalidRecordIDException e) {
                        logger.debug(e.toString());
                    }
                }
            }
            catch (RecordStoreNotOpenException e) {
                logger.warn(e.toString());
            }
            catch (RecordStoreException e) {
                logger.warn(e.toString());
            }

            try {
                logger.debug("Adding new ones to the store.");
                //boolean first=true;
                for (Enumeration e = records.keys(); e.hasMoreElements();) {
                    String key = (String) e.nextElement();
                    String tmp = key + "=" + (String) records.get(key);
                    logger.debug("add(" + tmp + ")");

                    //if (first) {
                    //	rs.setRecord(1, tmp.getBytes(), 0, tmp.getBytes().length);
                    //	first=false;
                    //}
                    //else
                    rs.addRecord(tmp.getBytes(), 0, tmp.getBytes().length);
                }
            }
            catch (RecordStoreNotOpenException e) {
                logger.warn(e.toString());
            }
            catch (RecordStoreException e) {
                logger.warn(e.toString());
            }
        }
    }

    /** Prints all items red from the record store. */
    public void printSettings() {
        logger.debug("Properties read from record store.");
        for (Enumeration keys = records.keys(); keys.hasMoreElements();) {
            String tmp = (String) keys.nextElement();
            logger.info(tmp);
        }
    }

    /** Get value.
     *
     * @param key
     * @return the value found by key or null.
     */
    public String get(String key) {
        logger.debug("get("+key+") = " + (String) records.get(key));
        return (String) records.get(key);
    }

    /** Puts key and value to the hashtable.
     *
     * @param key
     * @param val Value associated with key
     */
    public void put(String key, String val) {
        logger.debug("put("+key+") = " + val);
        records.put((String) key, (String) val);
    }
}
